﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Event_Planner
{
    public partial class Stand_Application : Form
    {
        DB db;    //db as the object of the class DB
        int selectedStandId, userId = 0, userId2 = 0;
        double totalAmount = 0;
        List<Stand> standList;

        public Stand_Application()
        {
            InitializeComponent();
            db = new DB();
            standList = getAllStands();
        }

        public List<Stand> getAllStands()
        {
            List<Stand> stands = new List<Stand>();
            //1. get all stands
            DataTable standRecords = db.getAllStandsFromDB();
            int standId;
            string standName;
            for (int i = 0; i < standRecords.Rows.Count; i++)
            {
                standId = Convert.ToInt32(standRecords.Rows[i]["stand_id"].ToString());
                standName = standRecords.Rows[i]["name"].ToString();
                Stand stand = new Stand(standId, standName);
               
                //2. get items for each shop
                stand.Materials = getStandMaterials(stand.Id);
                stands.Add(stand);
            }
            return stands;
        }

        public List<Material> getAllMaterials()
        {
            List<Material> materials = new List<Material>();
            DataTable materialRecords = db.getAllMaterialsFromDB();
            int materialId, materialQuantity;
            string materialName;
            double materialPrice;
            for (int i = 0; i < materialRecords.Rows.Count; i++)
            {
                materialId = Convert.ToInt32(materialRecords.Rows[i]["material_id"].ToString());
                materialName = materialRecords.Rows[i]["name"].ToString();
                materialPrice = Convert.ToDouble(materialRecords.Rows[i]["price"].ToString());
                materialQuantity = Convert.ToInt32(materialRecords.Rows[i]["quantity"].ToString());
                materials.Add(new Material(materialId, materialName, materialPrice, materialQuantity));
            }
            return materials;
        }

        public List<Material> getStandMaterials(int standId)
        {
            List<Material> materials = new List<Material>();
            DataTable materialRecords = db.getStandMaterialsFromDB(standId);
            int materialId, materialQuantity;
            string materialName;
            double materialPrice;
            for (int i = 0; i < materialRecords.Rows.Count; i++)
            {
                materialId = Convert.ToInt32(materialRecords.Rows[i]["material_id"].ToString());
                materialName = materialRecords.Rows[i]["name"].ToString();
                materialPrice = Convert.ToDouble(materialRecords.Rows[i]["price"].ToString());
                materialQuantity = Convert.ToInt32(materialRecords.Rows[i]["quantity"].ToString());
                materials.Add(new Material(materialId, materialName, materialPrice, materialQuantity));
            }
            return materials;
        }

        private void Stand_Application_Load(object sender, EventArgs e)
        {
            ////////////////////////////////////////////////////////////////////////////////////////////////////////

            this.cbStands.Items.Add("Select a stand");   //add the first items of the combo boxes 
            this.cbStands.SelectedIndex = 0;            //make it the default selected item
            //get all the stands
            foreach (Stand stand in standList)               //go through the list of stands and add their names to the combo box
            {
                this.cbStands.Items.Add(stand.Name);
            }


            //////////////////////////////////////////////////////////////////////////////////////////////////////////

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.txtQuantity.Text == "")
            {
                MessageBox.Show("Enter a quantity");
            }
            else
            {
                int quantity = Convert.ToInt32(this.txtQuantity.Text);
                if (quantity > 0)
                {
                    string selectedStandName = this.cbStands.SelectedItem.ToString();
                    string selectedMaterialName = this.cbMaterials.SelectedItem.ToString();
                    Material selectedMaterial = getMaterial(selectedStandId, selectedMaterialName);
                    double total = quantity * selectedMaterial.Price;
                    totalAmount += total;
                    if (!this.itemIsAlreadyAdded(selectedStandName, selectedMaterial.Name))
                    {
                        int user_Id = getUserId();
                        double balance = db.getUserBalance(user_Id);
                        if (balance >= totalAmount)
                        {
                            this.dataGridView1.Rows.Add(selectedMaterial.Name, quantity, selectedMaterial.Price, total, selectedStandName);
                            this.labelTotal.Text = totalAmount.ToString();
                        }
                        else
                        {
                            totalAmount -= total;
                            MessageBox.Show("Insufficient Balance, the item cannot be added!");
                        }
                    }
                    else
                    {
                        MessageBox.Show("The item is already added");
                    }
                }
                else
                {
                    MessageBox.Show("Enter a valid quantity");
                }
            }
        }

        public bool itemIsAlreadyAdded(string shopName, string itemName)
        {
            for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
            {
                //get the selected row
                DataGridViewRow selectedRow = dataGridView1.Rows[i];
                //get the selected item and shop
                string selectedItemName = selectedRow.Cells[0].Value.ToString();
                string selectedShopName = selectedRow.Cells[4].Value.ToString();
                if (selectedItemName == itemName && selectedShopName == shopName)
                {
                    return true;
                }
            }
            return false;
        }


        private void cbShops_SelectedIndexChanged(object sender, EventArgs e)
        {

            string selectedShopName = this.cbStands.SelectedItem.ToString();
            //MessageBox.Show(selectedShopName);
            if (selectedShopName != "Select a shop")
            {
                selectedStandId = getStandId(selectedShopName);
                if (selectedStandId != 0)
                {
                    this.cbMaterials.Items.Clear();
                    List<Material> items = getStandMaterials(selectedStandId);          //get all the items
                    foreach (Material item in items)               //go through the list of items and add their names to the combo box
                    {
                        this.cbMaterials.Items.Add(item.Name);
                    }
                    this.cbMaterials.SelectedIndex = 0;
                }
            }

        }

        //nethods
        public int getStandId(string shopName)
        {
            for (int i = 0; i < standList.Count; i++)
            {
                if (standList[i].Name == shopName)
                {
                    return standList[i].Id;
                }
            }
            return 0;
        }

       public Material getMaterial(int materialId, string materialName)
        {
          
           for (int i = 0; i < standList.Count; i++)
            {
                if (standList[i].Id == materialId)
                {
                    for (int j = 0; j < standList[i].Materials.Count; j++)
                    {
                        if (standList[i].Materials[j].Name == materialName)
                        {
                            return standList[i].Materials[j]; 
                        }
                    }
                }
            }
            return null;

           
        }




        private void btnRemove_Click(object sender, EventArgs e)
        {

            if (this.dataGridView1.Rows[0].Cells[0].Value != null)
            {
                for (int i = 0; i < this.dataGridView1.SelectedRows.Count; i++)
                {
                    int selectedRowIndex = this.dataGridView1.SelectedCells[i].RowIndex;
                    //MessageBox.Show(selectedRowIndex.ToString());
                    DataGridViewRow selectedRow = dataGridView1.Rows[selectedRowIndex];
                    double selectedTotal = Convert.ToDouble(selectedRow.Cells[3].Value);
                    totalAmount -= selectedTotal;
                    this.dataGridView1.Rows.RemoveAt(selectedRowIndex);
                }
                this.labelTotal.Text = totalAmount.ToString();
            }
            else
            {
                MessageBox.Show("You cannot remove an inexisting item!");
            }

        }

        private void btnIncrease_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.Rows[0].Cells[0].Value != null)
            {
                for (int i = 0; i < this.dataGridView1.SelectedRows.Count; i++)
                {
                    //get the index of the selected row
                    int selectedRowIndex = this.dataGridView1.SelectedCells[i].RowIndex;
                    //get the selected row
                    DataGridViewRow selectedRow = dataGridView1.Rows[selectedRowIndex];
                    //get the selected quantity, price and total
                    double selectedQuantity = Convert.ToInt32(selectedRow.Cells[1].Value);
                    double selectedPrice = Convert.ToDouble(selectedRow.Cells[2].Value);
                    double selectedTotal = Convert.ToDouble(selectedRow.Cells[3].Value);
                    //set the new quantity and total
                    selectedRow.Cells[1].Value = ++selectedQuantity;
                    selectedRow.Cells[3].Value = selectedPrice * selectedQuantity;
                    //subtract the old total from the totalAmount
                    totalAmount -= selectedTotal;
                    //add the new total to the total amount
                    totalAmount += selectedPrice * selectedQuantity;
                }
                this.labelTotal.Text = totalAmount.ToString();
            }
            else
            {
                MessageBox.Show("You cannot increase an inexisting quantity!");
            }
        }


        private void btnDecrease_Click(object sender, EventArgs e)
        {
            //check if the dataGridView is empty
            if (this.dataGridView1.Rows[0].Cells[0].Value != null)
            {
                for (int i = 0; i < this.dataGridView1.SelectedRows.Count; i++)
                {
                    //get the index of the selected row
                    int selectedRowIndex = this.dataGridView1.SelectedCells[i].RowIndex;
                    //get the selected row
                    DataGridViewRow selectedRow = dataGridView1.Rows[selectedRowIndex];
                    //get the selected quantity, price and total
                    double selectedQuantity = Convert.ToInt32(selectedRow.Cells[1].Value);
                    double selectedPrice = Convert.ToDouble(selectedRow.Cells[2].Value);
                    double selectedTotal = Convert.ToDouble(selectedRow.Cells[3].Value);
                    //set the new quantity and total. limit the minimum quantity to 1
                    if (selectedQuantity > 1)
                    {
                        selectedRow.Cells[1].Value = --selectedQuantity;
                    }

                    selectedRow.Cells[3].Value = selectedPrice * selectedQuantity;
                    //subtract the old total from the totalAmount
                    totalAmount -= selectedTotal;
                    //add the new total to the total amount
                    totalAmount += selectedPrice * selectedQuantity;
                }
                this.labelTotal.Text = totalAmount.ToString();
            }
            else
            {
                MessageBox.Show("You cannot decrease an inexisting quantity!");
            }
        }

        private void btnBuy_Click(object sender, EventArgs e)
        {
            if (this.txtUserId.Text == "")
            {
                MessageBox.Show("Enter the user's Id");
            }
            else
            {
                int user_Id = Convert.ToInt32(this.txtUserId.Text);
                if (user_Id > 0)
                {
                    double balance = db.getUserBalance(user_Id);
                    if (balance >= totalAmount)
                    {
                        //check if the dataGridView is empty
                        if (this.dataGridView1.Rows[0].Cells[0].Value != null)
                        {
                            for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
                            {
                                //get the selected row
                                DataGridViewRow selectedRow = dataGridView1.Rows[i];
                                //get the selected data
                                string selectedMaterialName = selectedRow.Cells[0].Value.ToString();
                                int selectedQuantity = Convert.ToInt32(selectedRow.Cells[1].Value);
                                double selectedPrice = Convert.ToDouble(selectedRow.Cells[2].Value);
                                double selectedTotal = Convert.ToDouble(selectedRow.Cells[3].Value);
                                string selectedShopName = selectedRow.Cells[4].Value.ToString();
                                int standId = this.getStandId(selectedShopName);
                                int materialId = this.getMaterial(standId, selectedMaterialName).Id;
                                db.insertParticipantMaterial(user_Id, materialId, selectedQuantity);
                            }
                            int accountNumber = db.getUserAccountNumber(user_Id);
                            db.withdrawParticipantAccount(accountNumber, totalAmount);
                            MessageBox.Show("The materials were successfully Hired");
                        }
                        else
                        {
                            MessageBox.Show("You need to add some materials first");
                        }
                    }
                    else
                    {
                        MessageBox.Show("The user's account balance is not enough for this purchase");
                    }
                }
                else
                {
                    MessageBox.Show("Enter a valid user Id");
                }
            }
        }

        private void btnReturn_Click(object sender, EventArgs e)
        {
            DataTable hiredMaterials = db.getUserMaterials(userId2);
            int materialId;
            double totalPrice = 0;
            for (int i = 0; i < hiredMaterials.Rows.Count; i++)
            {
                materialId = Convert.ToInt32(hiredMaterials.Rows[i]["material_id"]);
                db.updateParticipantMaterial(userId2, materialId);
                totalPrice += Convert.ToDouble(hiredMaterials.Rows[i]["price"]) * Convert.ToInt32(hiredMaterials.Rows[i]["quantity_hired"]);
            }
            int accountNumber = db.getUserAccountNumber(userId2);
            db.depositParticipantAccount(accountNumber, totalPrice);
            MessageBox.Show("The materials were successfully returned");
            this.listBox1.Items.Clear();

        }

        private void btnView_Click(object sender, EventArgs e)
        {
            if (this.txtUserId2.Text == "")
            {
                MessageBox.Show("Enter the user's Id");
            }
            else
            {
                int user_Id = Convert.ToInt32(this.txtUserId2.Text);
                if (user_Id > 0)
                {
                    userId2 = user_Id;
                    DataTable hiredMaterials = db.getUserMaterials(user_Id);
                    if (hiredMaterials.Rows.Count > 0)
                    {
                        string materialName, hireDate, result;
                        double price, total;
                        int quantityHired;
                        for (int i = 0; i < hiredMaterials.Rows.Count; i++)
                        {
                            materialName = hiredMaterials.Rows[i]["name"].ToString();
                            hireDate = hiredMaterials.Rows[i]["hire_date"].ToString();
                            price = Convert.ToDouble(hiredMaterials.Rows[i]["price"]);
                            quantityHired = Convert.ToInt32(hiredMaterials.Rows[i]["quantity_hired"]);
                            total = price * quantityHired;
                            result = (i + 1) + ". Material Name: " + materialName + "\n Quantity hired: " + quantityHired.ToString();
                            result += "\n Total price: " + total.ToString() + "\n Hire date: " + hireDate + "\n";
                            this.listBox1.Items.Add((i + 1) + ". Material Name: " + materialName);
                            this.listBox1.Items.Add("   Quantity hired: " + quantityHired.ToString());
                            this.listBox1.Items.Add("   Total price: " + total.ToString());
                            this.listBox1.Items.Add("   Hire date: " + hireDate);
                            this.listBox1.Items.Add("");
                        }
                    }
                    else
                    {
                        MessageBox.Show("There is no hired material for this user");
                    }
                }
                else
                {
                    MessageBox.Show("Enter a valid user Id");
                }
            }
        }

        private void cbStands_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedShopName = this.cbStands.SelectedItem.ToString();
            //MessageBox.Show(selectedShopName);
            if (selectedShopName != "Select a shop")
            {
                selectedStandId = getStandId(selectedShopName);
                if (selectedStandId != 0)
                {
                    this.cbMaterials.Items.Clear();
                    List<Material> items = getStandMaterials(selectedStandId);          //get all the items
                    foreach (Material item in items)               //go through the list of items and add their names to the combo box
                    {
                        this.cbMaterials.Items.Add(item.Name);
                    }
                    this.cbMaterials.SelectedIndex = 0;
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.txtUserId.Text == "")
            {
                MessageBox.Show("Enter the user's Id");
            }
            else
            {
                int user_Id = Convert.ToInt32(this.txtUserId.Text);
                if (user_Id > 0)
                {
                    double balance = db.getUserBalance(user_Id);
                    this.txtBalance.Text = balance.ToString();
                }
                else
                {
                    MessageBox.Show("Enter a valid user Id");
                }
            }
        }

        private int getUserId()
        {
            if (this.txtUserId.Text == "")
            {
                MessageBox.Show("Enter the user's Id");
            }
            else
            {
                int user_Id = Convert.ToInt32(this.txtUserId.Text);
                if (user_Id > 0)
                {
                    return user_Id;
                }
                else
                {
                    MessageBox.Show("Enter a valid user Id");
                }
            }
            return 0;
        }
    }
}
